<route lang="json5">
{
  style: {
    navigationBarTitleText: '我的',
    navigationBarBackgroundColor: '#FFFFFF',
  },
}
</route>

<template>
  <navbar leftIcon="" text="我的" />
  <view class="scroll">
    <view
      class="service public-page"
      :style="{ height: `calc(100vh - ${safeAreaInsets?.top}px - 44px - 54px)` }"
    >
      <view class="public-background">
        <scroll @scrollChange="scrollChange">
          <view class="public-height"></view>
          <view class="mys">
            <view class="information" v-if="isLogin">
              <view class="header-box">
                <view class="header">
                  <uv-avatar
                    size="138rpx"
                    :src="
                      information.avatarPath ||
                      `https://ai-ecg-beta.lifesense.com/resources/images/avator-${information.gender === 'F' ? 'F' : 'M'}.png`
                    "
                  ></uv-avatar>
                </view>
                <view class="phone-button">
                  <view style="width: 100%" class="ellipsis name">
                    {{ information.name }}
                  </view>
                  <wd-button size="small" type="info" plain hairline @click="informationPage">
                    完善个人信息 >
                  </wd-button>
                </view>
              </view>
              <view class="info mt-2" @tap.stop="loginOut">退出登录</view>
            </view>
            <view class="information no-login" v-else>
              <view class="header-box">
                <view class="header">
                  <uv-avatar
                    size="138rpx"
                    src="https://ai-ecg-beta.lifesense.com/resources/images/avator.png"
                  ></uv-avatar>
                </view>
                <view class="phone-button">
                  <view style="width: 100%">未登录</view>
                  <view style="width: 100%"></view>
                </view>
              </view>
              <wd-button block size="large" type="primary" @click="login">登录</wd-button>
            </view>
            <view class="device">
              <view class="device-left">
                <view class="title">
                  <uv-text bold block color="#000000" size="36rpx" text="我的设备"></uv-text>
                  <text
                    style="display: inline-block; margin: 18rpx 0; font-size: 24rpx; color: #000000"
                  >
                    {{ deviceLength ? `共${deviceLength}台已绑定` : `未绑定设备` }}
                    {{ isMonitorLength ? `，其中${isMonitorLength}台监测中` : '' }}
                    {{ isUploadLength ? `，其中${isUploadLength}台上传数据中` : '' }}
                  </text>
                </view>
                <view class="button" v-if="isLogin">
                  <view v-if="deviceLength" style="margin-right: 30rpx">
                    <uv-button
                      @click="device"
                      size="mini"
                      type="primary"
                      shape="circle"
                      customStyle="padding:26rpx 28rpx;font-size:24rpx;background:#E50038;border:none;"
                    >
                      点击查看
                    </uv-button>
                  </view>
                  <uv-button
                    size="mini"
                    type="primary"
                    shape="circle"
                    customStyle="padding:26rpx 22rpx;font-size:24rpx;background:#FBEDEC;border:none"
                    plain
                    @click="jumpHome"
                  >
                    绑定新设备
                  </uv-button>
                </view>
              </view>
              <view class="device-right">
                <uv-text
                  align="right"
                  suffixIcon="question-circle-fill"
                  color="#666666"
                  size="13"
                  @click="operating"
                  text="操作指引"
                ></uv-text>
                <uv-image
                  src="https://ai-ecg-beta.lifesense.com/resources/images/bind-icon-yellow.png"
                  width="180rpx"
                  height="180rpx"
                >
                  <template v-slot:loading>
                    <uv-loading-icon mode="spinner"></uv-loading-icon>
                  </template>
                </uv-image>
              </view>
            </view>
            <view class="device">
              <view class="device-left">
                <view class="title">
                  <uv-text bold block color="#000000" size="36rpx" text="我的报告"></uv-text>
                  <text
                    style="display: inline-block; margin: 18rpx 0; font-size: 24rpx; color: #000000"
                  >
                    {{ reportTotal ? `共${reportTotal}份报告` : `暂无报告` }}
                    {{ finishTotal ? `，其中${finishTotal}份已诊断` : '' }}
                  </text>
                </view>
                <view class="button" v-if="isLogin">
                  <view style="margin-right: 30rpx">
                    <uv-button
                      @click="report"
                      size="mini"
                      type="primary"
                      shape="circle"
                      customStyle="padding:26rpx 28rpx;font-size:24rpx;background:#E50038;border:none"
                    >
                      点击查看
                    </uv-button>
                  </view>
                  <uv-button
                    size="mini"
                    type="primary"
                    shape="circle"
                    customStyle="padding:26rpx 22rpx;font-size:24rpx;background:#FBEDEC;border:none"
                    plain
                    @click="lookPatientId"
                  >
                    查看用户ID
                  </uv-button>
                </view>
              </view>
              <view class="device-right">
                <view style="width: 100%; height: 20rpx"></view>
                <uv-image
                  src="https://ai-ecg-beta.lifesense.com/resources/images/report-red.png"
                  width="180rpx"
                  height="180rpx"
                >
                  <template v-slot:loading>
                    <uv-loading-icon mode="spinner"></uv-loading-icon>
                  </template>
                </uv-image>
              </view>
            </view>
            <view>
              <uv-text
                align="center"
                color="#cccccc"
                size="14"
                :customStyle="{ 'margin-top': '60rpx' }"
                text="———— &nbsp;&nbsp;&nbsp;当前版本：1.32 &nbsp;&nbsp;&nbsp;————"
              ></uv-text>
            </view>
          </view>
        </scroll>
      </view>
    </view>
  </view>
  <tabBar :current="2" ref="tabBarRef" />
</template>

<script lang="js" setup>
import tabBar from '@/custom-tab-bar'
import navbar from '@/components/navbar'
import scroll from '@/components/scrollView'
import { getDevices, getReportList, getUserInfo } from '@/service/index/default'
import { isLoginEd, clearUser, getUser, loginJump, setSn } from '@/utils/publicMethods'
import useScan from '@/pages/home/method/useScan'
import { subscribe } from '@/utils/publicMethods'
const { safeAreaInsets } = uni.getWindowInfo()
const { GetWxUrlParam } = useScan()
// 是否登录
const isLogin = ref(false)
const userInfo_ = ref({})

onShow(() => {
  const pages = getCurrentPages()
  const currPage = pages[pages.length - 1]
  const avatarUrl = currPage.data?.avatarUrl
  avatarUrl && (information.value.avatarPath = avatarUrl)
  resetData()
})

const scrollChange = () => {
  resetData()
}

const resetData = () => {
  isLogin.value = isLoginEd()
  if (!isLogin.value) {
    initData()
    return
  }
  userInfo_.value = getUser()
  getUserInfo_()
  getDevices_()
  getReportList_()
}

const initData = () => {
  deviceLength.value = 0
  isMonitorLength.value = 0
  isUploadLength.value = 0
  reportTotal.value = 0
  finishTotal.value = 0
  userInfo_.value = {}
  information.value = {}
}

// 获取用户基本信息
const information = ref({})
const getUserInfo_ = async () => {
  const name = userInfo_.value.phoneNumber.slice(-4) + '尾号用户'
  const { data, code, error } = await getUserInfo({ userId: userInfo_.value.userId })
  if (code !== 200) {
    information.value = {}
    information.value.name = name
    return false
  }
  information.value = data
  information.value.name = data.name || name
}

// 获取绑定设备列表
const deviceLength = ref(0)
const isMonitorLength = ref(0)
const isUploadLength = ref(0)
const getDevices_ = async () => {
  const { data, code, error } = await getDevices({ userId: userInfo_.value.userId })
  if (code !== 200) {
    deviceLength.value = 0
    isMonitorLength.value = 0
    isUploadLength.value = 0
    return false
  }
  deviceLength.value = data.length
  isMonitorLength.value = data.filter((item) => item.monitor === 1).length
  isUploadLength.value = data.filter((item) => item.upload === 2).length
}

// 获取报告列表
const reportTotal = ref(0)
const finishTotal = ref(0)
const getReportList_ = async () => {
  const { data, code, error } = await getReportList({ userId: userInfo_.value.userId })
  if (code !== 200) {
    reportTotal.value = 0
    finishTotal.value = 0
    return false
  }
  reportTotal.value = data.count
  // finishTotal.value = data.data.filter((item) => item.diagnosed === 1).length
}

const login = () => {
  uni.navigateTo({ url: '/pages-sub/login/index' }, 1000)
}

// 个人资料编辑
const informationPage = () => {
  uni.navigateTo({ url: '/pages-sub/information/index' }, 1000)
}

// 我的设备编辑
const device = () => {
  uni.navigateTo({ url: '/pages-sub/deviceList/index' }, 1000)
}

// 我的报告
const report = async () => {
  // 订阅
  await subscribe(userInfo_.value.userId)
  // 跳转报告列表页面
  uni.navigateTo({ url: '/pages-sub/viewReport/index' }, 1000)
}

// 操作指引
const operating = () => {
  uni.navigateTo({ url: '/pages-sub/operating/index' }, 1000)
}

//查看病人id
const lookPatientId = () => {
  uni.showModal({
    title: '用户ID',
    content: userInfo_.value.userId,
    showCancel: true,
    cancelText: '关闭',
    confirmText: '复制',
    confirmColor: '#e50038',
    cancelColor: '#999999',
    success: (res) => {
      if (res.confirm) {
        uni.setClipboardData({
          data: userInfo_.value.userId + '', //    这里是个坑接受字符串类型 value转化为字符串
          success: () => {
            uni.showToast({
              title: '复制成功',
              duration: 2000,
              icon: 'success',
            })
          },
        })
      }
    },
  })
}

// 跳转首页绑定
const jumpHome = () => {
  if (!isLogin.value) {
    loginJump()
    return
  }
  if (isMonitorLength.value) {
    uni.showToast({
      title: `请完成监测流程后再绑定新设备`,
      icon: 'none',
    })
    return
  }
  if (isUploadLength.value) {
    uni.showToast({
      title: `请等待数据上传完成后再绑定新设备`,
      icon: 'none',
    })
    return
  }
  uni.scanCode({
    barCodeInput: true,
    success: (res) => {
      const params = GetWxUrlParam(res?.result)
      if (!params?.sn && !params?.type) {
        uni.showToast({
          title: '未查询到有效参数',
          icon: 'none',
        })
        return false
      }
      uni.reLaunch(
        {
          url: `/pages/home/index?type=device&sn=${params.sn}&name=${params.name}&model=${params.model}`,
        },
        3000,
      )
    },
    fail: (err) => {
      console.log('扫描失败：', err)
    },
  })
}

const loginOut = () => {
  uni.showModal({
    title: '提示',
    content: '确定退出登录吗？',
    showCancel: true,
    cancelText: '取消',
    confirmText: '确定',
    confirmColor: '#e50038',
    cancelColor: '#999999',
    success: (res) => {
      if (res.confirm) {
        clearUser()
        setSn('')
        initData()
        isLogin.value = false
        uni.$emit('loginEvent', false)
      }
    },
  })
}

// -------------------微信分享----------------------
// 分享至好友/群聊
onShareAppMessage((res) => {
  return {
    title: '我的',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})
// 分享到朋友圈
onShareTimeline((res) => {
  return {
    title: '我的',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})
</script>

<style lang="scss" scoped>
.mys {
  .information {
    display: flex;
    align-items: start;
    justify-content: space-between;
    padding: 30rpx 36rpx 40rpx 30rpx;
    background: #ffffff;
    border-radius: 20rpx;
    .info {
      font-size: 26rpx;
      color: #666666;
    }
    .header-box {
      display: flex;
      align-items: center;
      width: 70%;
      .phone-button {
        display: flex;
        flex-wrap: wrap;
        align-content: space-around;
        width: 70%;
        height: 138rpx;
        margin-left: 30rpx;
        .name {
          font-size: 40rpx;
          font-weight: 600;
          color: #000000;
        }
        :deep(.is-plain) {
          background: none;
        }
      }
    }
  }
  .no-login {
    align-items: center;
    :deep(.is-large) {
      padding: 50rpx 70rpx;
    }
  }
  .device {
    display: flex;
    align-items: start;
    justify-content: space-between;
    height: 236rpx;
    padding: 30rpx 30rpx 32rpx 30rpx;
    margin-top: 30rpx;
    background: #ffffff;
    border-radius: 20rpx;
    .device-right {
      display: flex;
      flex-wrap: wrap;
      align-content: space-between;
      width: min-content;
      height: 100%;
    }
    .device-left {
      display: flex;
      flex-wrap: wrap;
      align-content: space-between;
      height: 100%;
      .title {
        width: 100%;
      }
      .button {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
      }
    }
  }
}
</style>
